Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

Solution:

  1. public class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. int i = 0, j = 0, max = 0;
  4. Set<Character> set = new HashSet<>();
  5. while (j < s.length()) {
  6. if (!set.contains(s.charAt(j))) {
  7. set.add(s.charAt(j++));
  8. max = Math.max(max, set.size());
  9. } else {
  10. set.remove(s.charAt(i++));
  11. }
  12. }
  13. return max;
  14. }
  15. }